package com.doit.day03.不可变集合

import scala.collection.immutable

object _14_平均温度 {
  def main(args: Array[String]): Unit = {
    val d1 = Array(("beijing", 28.1), ("shanghai", 28.7), ("guangzhou", 32.0), ("shenzhen", 31.0))
    val d2 = Array(("beijing", 27.3), ("shanghai", 30.1), ("guangzhou", 33.3))
    val d3 = Array(("beijing", 28.2), ("shanghai", 29.1), ("guangzhou", 32.0), ("shenzhen", 32.0))

    //要求：求出三天每个城市得平均温度 ==》 北京：28  上海  29   广州 32 深圳 31.5

    //1.将每一天的城市温度都放在一个Array
    val tuples: Array[(String, Double)] = d1 ++ d2 ++ d3

    //2.根据城市进行分组 ==》 Map ==》 城市  Array((城市,温度))
    val maped: Map[String, Array[(String, Double)]] = tuples.groupBy(_._1)

    //3.Map映射  城市取出来    对value这个数组再进行映射  将第二个取出来做sum / Array的长度
    maped.map(tp=>{
      val city: String = tp._1
      val cityAndTep: Array[(String, Double)] = tp._2
      //对value这个数组再进行映射
      val avg = (cityAndTep.map(_._2).sum/cityAndTep.size).formatted("%.2f").toDouble
      (city,avg)
    }).foreach(println)


    val tuples1: Array[(String, Double)] = d1 ++ d2 ++ d3
    tuples1.groupBy(_._1)
      .map(tp=>(tp._1,(tp._2.map(_._2).sum/tp._2.size).formatted("%.2f").toDouble))
      .foreach(println)


    //1.放在一个Array中

    //val tuples: Array[(String, Double)] = d1 ++ d2 ++ d3

   /* val array: Array[Array[(String, Double)]] = Array(d1, d2, d3)
    //2.然后做flatten，取出每一个元祖
    val flatten: Array[(String, Double)] = array.flatten
    //3.按照city进行分组  shenzhen  Array(("shenzhen", 31.0)) ,("shenzhen", 32.0))
    val stringToTuples: Map[String, Array[(String, Double)]] = flatten.groupBy(_._1)
    //取出元祖中的温度进行计算
    //    val iterable: immutable.Iterable[Array[(String, Double)]] = stringToTuples.map(_._2.map(tp => (tp._1, tp._2)))
    stringToTuples.map(tp => {
      //Array(("shenzhen", 31.0)) ,("shenzhen", 32.0))
      val value: Array[(String, Double)] = tp._2

      //Array里面全部放的是温度
      val sum: Double = value.map(tp => tp._2).sum
      val avg = (sum/value.size).formatted("%.2f").toDouble
      (tp._1,avg)
    }).foreach(println)*/


  }

}
